#!/usr/bin/python
# -*- coding: UTF-8 -*-

import os
import util
import shutil
import platform


class Initializer:
    def check(self):
        return False

    # frontend 是用于多语言的idl生成这里的构建应该放在基础类里面
    def build_frontend(self):
        os.chdir("rpc-frontend")
        file = open("CMakeLists.txt", "w")
        file.write("cmake_minimum_required(VERSION 3.5)\n")
        if platform.system() == "Windows":
            file.write("set(CMAKE_CXX_STANDARD 17)\n")
        file.write("project (rpc-frontend)\n")
        file.write('INCLUDE_DIRECTORIES(${PROJECT_SOURCE_DIR}/src ${PROJECT_SOURCE_DIR}/src/thirdparty)\n')
        file.write('add_executable(rpc-frontend src/frontend.cpp src/json_builder.cpp src/parser.cpp '
                   'src/tokenizer.cpp src/md5.cpp src/main.cpp src/thirdparty/jsoncpp/json_writer.cpp '
                   'src/thirdparty/jsoncpp/json_value.cpp)\n')
        file.write("SET(EXECUTABLE_OUTPUT_PATH ${PROJECT_SOURCE_DIR}/../../bin)\n")
        file.write("IF (MSVC)\n")
        file.write('    set_target_properties(rpc-frontend PROPERTIES COMPILE_FLAGS "/EHa /wd4819 /wd4996")\n')
        file.write("ELSEIF(UNIX)\n")
        file.write('    if ("${CMAKE_CXX_COMPILER_ID}" STREQUAL "Clang")\n')
        file.write('        SET(CMAKE_CXX_FLAGS "' + self.options.get_option("cpp",
                                                                             "machine") + ' -g -O2 -std=c++17 -Wall -fPIC")\n')
        file.write('        set(CMAKE_CXX_COMPILER "clang++")\n')
        file.write('    elseif ("${CMAKE_CXX_COMPILER_ID}" STREQUAL "GNU")\n')
        file.write('        SET(CMAKE_CXX_FLAGS "' + self.options.get_option("cpp",
                                                                             "machine") + ' -g -O2 -std=c++17 -Wall -fPIC")\n')
        file.write('        set(CMAKE_CXX_COMPILER "g++")\n')
        file.write('    endif()\n')
        file.write("ENDIF ()\n")
        file.close()
        if platform.system() == "Windows":
            os.system('cmake -G  "Visual Studio 16 2019" -A x64')
            os.system('cmake --build . --config "Release"')
            shutil.copyfile("../../bin/Release/rpc-frontend.exe", "../../bin/rpc-frontend.exe")
            shutil.rmtree("../../bin/Release/")
        else:
            os.system("cmake -DDCMAKE_C_COMPILER=gcc  -DCMAKE_CXX_COMPILER=g++ .")
            os.system("make")
        os.chdir("..")

    def build_backend(self):
        pass

    # 因为要编译frontend 所以需要检查c++的编译器
    # 所有的环境准备都放到python里面
    # 准备protobuf的环境
    def checkPrecondition(self):
        if not util.check_git_env():
            return False

        if not util.check_compiler_env():
            return False

        # pb 没有初始话成功 直接退出
        if not util.check_pb_env():
            return False

        return True

    def init(self):
        return self.checkPrecondition()

    def checkEnv(self):
        pass


class Builder:
    def __init__(self, options):
        self.options = options

    def check_idl_name(self, idl_name):
        if idl_name.endswith(".idl"):
            return idl_name
        else:
            return idl_name + ".idl"

    def deleteIdl(self, name):
        idl_name = self.check_idl_name(name)
        if not os.path.exists("src/idl/" + idl_name):
            print (name + " not found in repo.")
            return
        (base_name, _) = os.path.splitext(os.path.basename(idl_name))
        if os.path.exists("src/include/" + base_name):
            shutil.rmtree("src/include/" + base_name)
        if os.path.exists("src/proxy/" + base_name):
            shutil.rmtree("src/proxy/" + base_name)
        if os.path.exists("src/stub/" + base_name):
            shutil.rmtree("src/stub/" + base_name)
        if os.path.exists("src/idl/" + base_name + ".idl"):
            os.remove("src/idl/" + base_name + ".idl")
        if os.path.exists("src/" + base_name):
            shutil.rmtree("src/" + base_name)
        if os.path.exists("lib/" + base_name):
            shutil.rmtree("lib/" + base_name)
        if os.path.exists("lib/proxy/" + base_name):
            shutil.rmtree("lib/proxy/" + base_name)
        if os.path.exists("lib/stub/" + base_name):
            shutil.rmtree("lib/stub/" + base_name)
        if os.path.exists("tmp/" + base_name):
            shutil.rmtree("tmp/" + base_name)

    def updateIdl(self, name, service_name=None):
        idl_name = self.check_idl_name(name)
        if not os.path.exists("src/idl/" + idl_name):
            print (name + " not found in repo.")
            return
        if not os.path.exists("src/idl/" + idl_name):
            return
        else:
            self.addIdl2Repo(idl_name, service_name, False)

    def build_idl(self, name, sname=None):
        pass

    # @title 构建测试server
    def build_beta_server(self, file_name, sname=None):
        pass

    def addIdl2Repo(self, file_name, sname=None, add=True):
        pass
        
    def build_sdk(self, name, sname=None):
        pass

    def updateRoot(self):
        pass
